package com.imclient.server;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.ArrayList;

import com.imclient.listener.ReceiveListener;
import com.imclient.message.Header;
import com.imclient.message.Message;
import com.imclient.type.HeaderType;

public class ReceiveServer {
	
	
	private static final int bytelength = 75;

	private InputStream ips;
	private ReceiveListener messageListener;
	

	public ReceiveServer(InputStream ips,ReceiveListener messageListener) {
		this.ips = ips;
		this.messageListener = messageListener;
	}

	public void Receives() throws Exception{
			while(true){
					Receive();
			}
	}
	void Receive() throws Exception {
		if (ips != null) {
			byte[] bs = new byte[bytelength];
			ByteArrayOutputStream bsa = new ByteArrayOutputStream();
			while (true) {
				if (ips == null) {

				}
				int length = ips.read(bs);
				if (length == -1) {
					throw new Exception();
				}
				bsa.write(bs, 0, length);
				byte[] dc = bsa.toByteArray();
				int len = dc.length;
				if ((dc[len-4 ] == '-' && dc[len - 3] == '\r'&& dc[len - 2] == '\n' && dc[len-1 ] == '-')) {
					break;
				}
			}
			
			ReceiveMsg(bsa.toByteArray());
		}

	}

	private void ReceiveMsg(byte... bys) {
		
		
		
		int start = 0;
		for(int i =0 ;i<bys.length;i++){
			if((bys.length>=i+3)&&(bys[i] == '-' && bys[i+1] == '\r'&& bys[i+2] == '\n' && bys[i+3] =='-')){
				i=i+4;
				start = i;
			}
			if((bys.length>=i+3)&&(bys[i] == '\r' && bys[i+1] == '\n'&& bys[i+2] == '\r' && bys[i+3] == '\n')){
				
				
				int bodylength = 0;
				Message msg = new Message();
				ArrayList<Header> hlist = new ArrayList<Header>();
				byte[] hb = new byte[i-start];
				System.arraycopy(bys,start, hb, 0, hb.length);
				String headerstr = new String(hb);
				
				
				String[] sa = headerstr.split("\r\n");
				for(String s:sa){
					if(s.length()>0){
						String h[]=s.split(":");
						Header hd = new Header();
						hd.setKey(h[0]);
						if(h[0].equals(HeaderType.Length.name())){
							bodylength = Integer.parseInt(h[1].trim());
						}
						hd.setValue(h[1]);
						hlist.add(hd);
						
					}
					
				}
				msg.setHeaders(hlist.toArray(new Header[]{}));
				if(bodylength>0){
					byte[] bodys = new byte[bodylength];
					msg.setBody(bodys);
					System.arraycopy(bys,i+4, bodys, 0, bodylength);
				}else{
					msg.setBody(new byte[0]);
				}
				messageListener.receiveMessage(msg);
				i = i+bodylength;
			}
		}
		
	}
	

}
